package javango.forms.widgets;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javango.forms.fields.ChoiceField;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RadioWidget<K,V> extends AbstractChoicesWidget<K,V> {

	public static class RadioInput extends AbstractWidget {

		Object choice_value;
		String choice_label;
		
		public RadioInput(Map<String, Object> attrs, Object choice_value, String choice_label) {
			super(attrs);
			this.choice_label = choice_label;
			this.choice_value = choice_value == null ? "" : choice_value;
		}

		public String getInputType() {
			return "radio";
		}
		
		@Override
		public String render(String name, Object value,	Map<String, Object> attrs) {
			Map<String, Object> finalAttrs = buildAttrs(attrs);
			finalAttrs.put("type", getInputType());
			finalAttrs.put("name", name);
			
			// TODO the id needs to contain a unique identifier
			if (finalAttrs.containsKey("id")) {
				finalAttrs.put("id", String.format((String)finalAttrs.get("id"), name));
			}
			
			finalAttrs.put("value", choice_value);
			
			if (StringUtils.equals(choice_value.toString(), value == null ? "" : value.toString())) {
				finalAttrs.put("checked", "checked");
			}
					
			return String.format("<label><input%s /> %s</label>", Util.flatatt(finalAttrs), choice_label);
		}
		
	}
	
	private final static Log log = LogFactory.getLog(RadioWidget.class);

	public RadioWidget(Map<K,V> choices) {
		super(null);
		setChoices(choices);
	}
	
	public RadioWidget() {
		super(null);	
	}
	
	
	public RadioWidget(Map<String, Object> attrs, Map<K,V> choices) {
		super(attrs);
		setChoices(choices);
	}
	
	public String render(String name, Object value, Map<String, Object> attrs) {
		if (value instanceof String[]) {
			String[] myvalue = (String[])value;
			if (myvalue.length > 0) {
				value = myvalue[0];
			} else {
				value = "";
			}
		}
		Map<String, Object> finalAttrs = buildAttrs(attrs);
		finalAttrs.put("name", name);
		
		if (finalAttrs.containsKey("id")) {
			finalAttrs.put("id", String.format((String)finalAttrs.get("id"), name));
		}
		
		StringBuilder b = new StringBuilder("<ul>\n");
		
		// TODO add a null choice,  need to add a method to choice field (getBlankText) that returns the correct text for a null or blank entry
//		if (isAddBlankEntry()) {
//			b.append(String.format(optionHtml, "", "", "--"));
//		}
		
		for(Entry<K,V> e : getChoices().entrySet()) {
			b.append("<li>");
			b.append(new RadioInput(attrs, e.getKey(), e.getValue().toString()).render(name, value, attrs));
			b.append("</li>\n");
		}

		b.append("</ul>");
		return b.toString();
	}

}
